package 前K个高频元素347;

import java.util.*;

/**
 * @author 谢阳
 * @version 1.8.0_131
 */
class Solution {
    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        int[] ints = topKFrequent(nums, k);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.putIfAbsent(num, 0);
            map.put(num, map.get(num) + 1);
        }
        PriorityQueue<Map.Entry<Integer, Integer>> heap =
                new PriorityQueue<>(
                        Comparator.comparingInt(Map.Entry::getValue));
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (heap.size() < k || heap.peek().getValue() < entry.getValue()) {
                heap.offer(entry);
            }

            if (heap.size() > k) {
                heap.poll();
            }
        }
        int[] ints = new int[k];
        for (int i = k - 1; i >= 0; i--) {
            ints[i] = heap.poll().getKey();
        }

        return ints;
    }
}